'''
Created on 15/05/2009

@author: eh01
'''
from yarra.datastore.dao import DSODAO
from yarra.datastore.dscache import DSCacheNotFoundException
class DefaultDSODAO(DSODAO):
        
    def __init__(self, dso_dao_impl, ds_cache):
        self.__dso_dao_impl = dso_dao_impl
        self.__ds_cache = ds_cache
            
    def save(self, dsos):
        dsos = self.__dso_dao_impl.save(dsos)
        self.__ds_cache.save(dsos)
        return dsos
    
    def find_by_id_and_version(self, id, version):
        try:
            return self.__ds_cache.find_by_id_and_version(id, version)
        except DSCacheNotFoundException:
            dso = self.__dso_dao_impl.find_by_id_and_version(id, version)
            self.__ds_cache.set_by_id_and_version(dso)
            return dso
    
    def find_by_ids(self, ids):
        try:
            return [self.__ds_cache.find_by_id(id) for id in ids]
        except DSCacheNotFoundException:
            dsos = self.__dso_dao_impl.find_by_ids(ids)
            for dso in dsos:
                self.__ds_cache.set_by_id(dso)
            return dsos
    
    def find_by_URI_and_version(self, uri, version):
        try:
            return self.__ds_cache.find_by_URI_and_version(uri, version)
        except DSCacheNotFoundException:
            dso = self.__dso_dao_impl.find_by_URI_and_version(uri, version)
            self.__ds_cache.set_by_URI_and_version(dso)
            return dso
    
    def find_by_URIs(self, uris):
        dsos = []
        uris_not_in_cache = []
        for uri in uris:
            try:
                dso = self.__ds_cache.find_by_URI(uri)
                dsos.append(dso)
            except DSCacheNotFoundException:
                uris_not_in_cache.append(uri)
        if uris_not_in_cache:
            dsos_not_in_cache = self.__dso_dao_impl.find_by_URIs(uris)
            for dso in dsos_not_in_cache:
                self.__ds_cache.set_by_URI(dso)
            dsos.extend(dsos_not_in_cache)            
        return dsos
    
    def find_versions(self, id):
        try:
            return self.__ds_cache.find_versions(id)
        except DSCacheNotFoundException:
            versions = self.__dso_dao_impl.find_versions(id)
            self.__ds_cache.set_versions(id, versions)
            return versions
    
    def remove(self, dsos):
        self.__dso_dao_impl.remove(dsos)
        self.__ds_cache.remove(dsos)
        
    def clear_cache(self):
        self.__ds_cache.clear_cache()